import React, { Component } from 'react'
import './index.css'

const MyContext = React.createContext()
const { Provider, Consumer } = MyContext

export default class Demo extends Component {
    state = { username: 'Tom', age: 18 }

    render() {
        const { username, age } = this.state
        return (
            <div className='parent'>
                <h3>我是A组件</h3>
                <h4>我的用户名叫：{username},年龄是：{age}</h4>
                <Provider value={{ username, age }}>
                    <B />
                </Provider>
            </div>
        )
    }
}

class B extends Component {
    render() {
        return (
            <div className='child'>
                <h3>我是B组件</h3>
                {/* <h4>我接收到的A用户名叫：{this.props.username}</h4> */}
                <C />
                <D />
            </div>
        )
    }
}

class C extends Component {
    static contextType = MyContext

    render() {
        return (
            <div className='grand'>
                <h3>我是C组件</h3>
                <h4>我接收到的A用户名叫：{this.context.username},年龄：{this.context.age}</h4>
            </div>
        )
    }
}

function D() {
    return <div className='grand'>
        <h3>我是D组件</h3>
        <h4>我接收到的A用户名叫：
            <Consumer>
                {
                    value => `${value.username},年龄是:${value.age}`
                }
            </Consumer>
        </h4>
    </div>
}
